<template>
  <el-dialog
      title="权限设置"
      :visible="visible"
      :close-on-click-modal="false"
      v-el-drag-dialog
      @close="onClose"
      @open="onOpen"
      width="400px"
  >
    <el-tree
        ref="menuTree"
        :data="menuTree"
        show-checkbox
        default-expand-all
        node-key="id"
        highlight-current
        :props="{children: 'children',label: 'label'}"
    />
    <div slot="footer">
      <el-button @click="onClose">取 消</el-button>
      <el-button type="primary" @click="onSubmit">确 定</el-button>
    </div>
  </el-dialog>
</template>

<script>
  import sysMenuApi from '@/api/sysMenu'
  import sysRoleApi from '@/api/sysRole'

  export default {
    props: {
      visible: {
        type: Boolean,
        default: false
      },
      row: {
        type: Object,
        default: function() {
          return null
        }
      },
      callback: {
        type: Function,
        default: function() {
          if (this.$parent.$refs.dataTable) {
            this.$parent.$refs.dataTable.getDataList()
          }
        }
      }
    },
    data() {
      return {
        menuTree: []
      }
    },
    methods: {
      onSubmit() {
        const menuIds = this.$refs.menuTree.getCheckedKeys().concat(this.$refs.menuTree.getHalfCheckedKeys()).join(',')
        sysRoleApi.bindMenu({
          roleId: this.row.id,
          menuIds
        }).then(res => {
          this.callback()
          this.onClose()
          this.$notify({
            title: '成功',
            message: '菜单权限设置成功',
            type: 'success'
          })
        })
      },
      createMenuTree(list = []) {
        return list.map(item => {
          return {
            id: item.id,
            label: item.title,
            children: this.createMenuTree(item.children)
          }
        })
      },
      createKeys(list) {
        const keys = []
        list.forEach(item => {
          const children = item.children
          if (children.length) {
            keys.push(...this.createKeys(children))
          } else {
            keys.push(item.id)
          }
        })
        return keys
      },
      onOpen() {
        sysMenuApi.listTree(1).then(res => {
          this.menuTree = this.createMenuTree(res.data)
          sysRoleApi.menuTree(this.row.id).then(res => {
            this.$refs.menuTree.setCheckedKeys(this.createKeys(res.data))
          })
        })
      },
      onClose() {
        this.$refs.menuTree.setCheckedKeys([])
        this.$emit('update:visible', false)
      }
    },
    mounted() {

    }
  }
</script>

<style scoped>

</style>
